<template>
  <div>
    <el-upload class="upload-demo" action="" :on-change="handleChange" :on-remove="handleRemove"
      :on-exceed="handleExceed" accept=".xls, .xlsx" :auto-upload="false" :limit="2">
      <el-button size="middle" :type = "ty" :style = "sy">上传资料</el-button>
    </el-upload>

     <!-- <div v-if="dalen>0" style="margin-top: 20px;">
      <el-table :data="da" style="width: 100%;">
        <el-table-column prop="zclx" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcly" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcnr" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcfwsj" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcsyh" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcwh" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zczt" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="cxsj" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcfbsj" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="cx" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcmc" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zhxgsj" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="zcjb" show-overflow-tooltip>
        </el-table-column>
      </el-table> -->
  </div>
</template>

<script>
  export default {
    name: "importExcel",

    props: {
      ty:{
        type: String,
        default: "primary"
      },
      sy:{
        type: String,
        default: ""
      }
    },
    data() {
      return {
        da: [],
        dalen: 0,
      }
    },

    // mounted () {
    //     this.init()
    // },

    methods: {
      // init() {
      //   let obj = {};
      //   let Jdata = localStorage.getItem("message");
      //   if (Jdata != null) {
      //     let temp = JSON.parse(Jdata)
      //     var t = temp[0]
      //     let o = []
      //     console.log(t.length)
      //     for (var i = 1; i < t.length; i++) {
      //       o[i - 1] = t[i]
      //     }
      //      console.log(JSON.stringify(o))
      //     this.da = o
      //     if (this.da != []) {
      //       this.dalen = this.da.length
      //     }
      //   }
      // },


      //上传文件时的处理办法
      handleChange(file, fileList) {
        if (fileList.length > 1) {
          fileList.splice(0, 1)
        }

        this.fileTemp = file.raw;
        if (this.fileTemp) {
          if ((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') ||
            (this.fileTemp.type == 'application/vnd.ms-excel')) {
            this.importfxx(this.fileTemp);
          } else {
            this.$message({
              type: 'warning',
              message: '附件格式错误，请删除后重新上传！'
            })
          }
        } else {
          this.$message({
            type: 'warning',
            message: '请上传附件！'
          })
        }
      },
      //超出最大上传文件数量时的处理方法
      handleExceed() {
        this.$message({
          type: 'warning',
          message: '超出最大上传文件数量的限制！'
        })
        return;
      },
      //移除文件的操作方法
      handleRemove(file, fileList) {
        this.fileTemp = null
      },
      importfxx(obj) {
        let _this = this;
        let inputDOM = this.$refs.inputer;
        // 通过DOM取文件数据

        this.file = event.currentTarget.files[0];

        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;

        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function (f) {
          var binary = "";
          var rABS = false; //是否将文件读取为二进制字符串
          var pt = this;
          var wb; //读取完成的数据
          var outdata;
          var reader = new FileReader();
          reader.onload = function (e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            //此处引入，用于解析excel
            var XLSX = require("xlsx");
            if (rABS) {
              wb = XLSX.read(btoa(fixdata(binary)), {
                //手动转化
                type: "base64"
              });
            } else {
              wb = XLSX.read(binary, {
                type: "binary"
              });
            }
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], {
              header: 1,
              defval: ''
            });
            //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
            //此处可对数据进行处理
            let arr = [];
            outdata.map(v => {
              let obj = {}
              obj.zcfwsj = v[0]
              obj.zcly = v[1]
              obj.zcwh = v[2]
              obj.cx = v[3]
              obj.zcsyh = v[4]
              obj.zcfbsj = v[5]
              obj.zcnr = v[6]
              obj.cxsj = v[7]
              obj.zczt = v[8]
              obj.zcmc = v[9]
              obj.zclx = v[10]
              obj.zhxgsj = v[11]
              obj.zcjb = v[12]
              arr.push(obj)
            });
            _this.da = arr;
            _this.dalen = arr.length;
            //_this.save()
            return arr;
          };
          reader.readAsArrayBuffer(f);
        };
        if (rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }
      },
      //将数据保存到localStorage
      save() {
        var obj = JSON.parse(localStorage.getItem("message") || '[]') //解析json
        //obj.unshift(this.da)
        obj = this.da
        localStorage.setItem('message', JSON.stringify(obj)) //将js对象转换为字符串
        var fdata = JSON.stringify(obj)
        // let postData = this.$qs.stringify({
        //   'Jsondata' : "1"
        // })

        this.$http.post(process.env.VUE_APP_BASE_API + "/common/excel", {
          postData: this.da
        }).then(res => {
          if (res.body.code == "500") {
            this.fail(res.body.msg)
          }
          if (res.body.code == "200") {
            this.open()
          }
        })
      },
      open() {
        this.$alert('excel上传成功！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `已确认`
            });
          }
        });
      },
      fail(msg) {
        this.$alert(msg, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `已确认`
            });
          }
        });
      }
    }
  }

</script>
<style>

</style>
